import { viewerDefaultConfig } from './config'
import { initMap, getMapLayer, removeLayer, addMutilOlOverlay, getConfigLayers, createLayer, updateLayers, disposeLayer, disposeControl, disposeInteraction, disposeRemoveOverlay } from './utils'
import { deepAssign } from '@/utils/tools/index.js'

export default class OlMap {
  constructor(_id, _option = {}) {
    this.id = _id
    this.options = deepAssign(viewerDefaultConfig, _option)
    // this.options.mapLayers = getConfigLayers(this.options.mapLayers)
    this.map = initMap(this).map
    if (this.options.locationConfig.show) { //  显示定位图标
      this.addLayer(this.options.locationConfig)
    }

  }
  /**
   * 新增加overlayer
   */
  addOverLayers(overlay) {
   
    addMutilOlOverlay(this.map, overlay)
  }
  /**
   * 跟新layer
   * @param {*} layer 
   */
  updateLayer(layer) {
    updateLayers(this.map, layer)
  }
  /**
   * 跟新多个layers
   * @param {*} layers 
   */
  updateMultipleLayer(layers) {
    if (layers) {
      for (let layer of layers) {

        this.updateLayer(layer)
      }
    }
  }
  /**
   * 添加Layer
   * @param {*} layer
   */
  addLayer(layer) {
    createLayer(this.map, layer)
  }

  addLayers(layers) {
    if (layers) {
      for (let layer of layers) {
        this.addLayer(layer)
      }
    }

  }

  getLayer(key, value) {
    return getMapLayer(this.map, key, value)
  }
  /**
   * 
   * @param {*} key  图层标志
   * @param {*} value 标志所用的名称(id,name)这些
   */
  onRemoveLayer(key, value) {
    // console.log('删除')
    removeLayer(this.map, key, value)
  }


  /**
 * 注销地图
 */
  destroy() {
    if (this.map) {
      // console.log('注销')

      disposeInteraction(this.map)
      disposeControl(this.map)
      disposeRemoveOverlay(this.map)
      disposeLayer(this.map)
      this.map = null
    }
  }

  exoprt() {
    this.map.once('rendercomplete', function () {
      var mapCanvas = document.createElement('canvas');
      var size = [100,100];
      mapCanvas.width = size[0];
      mapCanvas.height = size[1];
      var mapContext = mapCanvas.getContext('2d');
      Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function (canvas) {
        if (canvas.width > 0) {
          var opacity = canvas.parentNode.style.opacity;
          mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
          var transform = canvas.style.transform;
          var matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number);
          CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix);
          mapContext.drawImage(canvas, 0, 0);
        }
      });
      var data;
      if (navigator.msSaveBlob) {
        data = mapCanvas.toDataURL();
      } else {
        data = mapCanvas.toDataURL();
      }
      callback(data);
    });
    this.map.renderSync();

  }
}
